//
//  XGSettingTableViewController.m
//  Instagram
//
//  Created by monkey on 2019/4/20.
//  Copyright © 2019 itcast. All rights reserved.
//

#import <MJExtension/MJExtension.h>
#import <SVProgressHUD/SVProgressHUD.h>

#import "XGSettingTableViewController.h"

#import "XGSettingGroupModel.h"

#import "NSFileManager+Extension.h"

@interface XGSettingTableViewController ()

/// 设置模型数组
@property (nonatomic,strong) NSArray<XGSettingGroupModel *> *groups;

@end

@implementation XGSettingTableViewController
{
    /// plist文件名
    NSString *_plistName;
}

#pragma mark - 构造方法

- (instancetype)init
{
    @throw [NSException exceptionWithName:@"创建对象失败" reason:@"请使用指定构造方法 -initWithPlistName: 或类方法 +viewControllerWithPlistName创建对象" userInfo: nil];
}

- (instancetype)initWithPlistName:(NSString *)plistName
{
    if (self = [super initWithStyle:UITableViewStyleGrouped]) {
        _plistName = plistName;
    }
    
    return self;
}

+ (instancetype)viewControllerWithPlistName:(NSString *)plistName
{
    return [[self alloc] initWithPlistName:plistName];
}

#pragma mark - 控制器生命周期方法

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.tableView.tableFooterView = [[UIView alloc] init];
}

#pragma mark - 数据源和代理方法

// 多少组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.groups.count;
}

// 多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.groups[section].items.count;
}

// 每行的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XGSettingItemModel *item = self.groups[indexPath.section].items[indexPath.row];
    // 获取cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:item.style];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:[self tableViewCellStyleWithStyle:item.style] reuseIdentifier:item.style];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.separatorInset = UIEdgeInsetsZero;
    }

    cell.textLabel.text = item.title;

    // 如果有detailText设置detailText
    if (item.detailText != nil) {
        cell.detailTextLabel.text = item.detailText;
        if ([item.title isEqualToString:@"清除缓存"]) {
            // 清除缓存 计算cache目录的大小并赋值给detailText
            NSString *cachePath =  NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
            [NSFileManager getFileSize:cachePath completion:^(NSUInteger fileSize) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2f MB",fileSize / 1000.f / 1000.f];
                });
            }];
        }
    } else {
        // 没有detailText 设置accessoryType为箭头
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    return cell;
}

// 选中每行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    XGSettingItemModel *item = self.groups[indexPath.section].items[indexPath.row];
    // 如果有下一个控制器 则跳转
    if (item.plistName != nil && item.pushViewController != nil) {
        Class pushViewControllerClass = NSClassFromString(item.pushViewController);
        if (pushViewControllerClass != nil) {
            UIViewController *viewController = [[pushViewControllerClass alloc] initWithPlistName:item.plistName];
            viewController.navigationItem.title = item.title;
            [self.navigationController pushViewController:viewController animated:YES];
        }
    } else if (item.funcName != nil) {
        // 如果有监听方法
        SEL sel = NSSelectorFromString(item.funcName);
        if ([self respondsToSelector:sel]) {
            IMP imp = [self methodForSelector:sel];
            void (*func)(id, SEL) = (void *)imp;
            func(self,sel);
            // 替代[self performSelector:<#(SEL)#>] 这种方式调用动态方法 会产生警告
        }
    } else {
        // 没有控制器也没有监听方法 占位
        return;
    }
}

#pragma mark - 其他方法

/**
 更加cell样式字符串返回UITableViewCellStyle

 @param style 样式字符串
 @return UITableViewCellStyle
 */
- (UITableViewCellStyle)tableViewCellStyleWithStyle:(NSString *)style
{
    if ([style isEqualToString:@"UITableViewCellStyleValue1"]) {
        return UITableViewCellStyleValue1;
    } else {
        return UITableViewCellStyleDefault;
    }
}

/// 退出登录
- (void)logOut
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您确定要退出登录吗?" preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        // 退出登录
        [XGAccountViewModel logOut];
        // 发布通知 切换应用程序根控制器
        [[NSNotificationCenter defaultCenter] postNotificationName:kSwitchApplicationRootViewControllerNotification object:nil];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

/// 清除缓存
- (void)clearCache
{
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    DEBUG_Log(@"%@",cachePath);
    [NSFileManager removeFilePath:cachePath completion:^(NSError * _Nullable error) {
        if (error != nil) {
            DEBUG_Log(@"清除缓存失败 %@",error.localizedFailureReason);
            return;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showSuccessWithStatus:@"清除成功!"];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            cell.detailTextLabel.text = @"0.0 MB";
        });
    }];
}

#pragma mark - 懒加载

- (NSArray<XGSettingGroupModel *> *)groups
{
    if (!_groups) {
        _groups = [XGSettingGroupModel mj_objectArrayWithFilename:_plistName];
    }
    
    return _groups;
}

@end
